package com.easy.service.impl;

import com.easy.annotation.LogMethod;
import com.easy.bean.PasswordParam;
import com.easy.bean.User;
import com.easy.mapper.UserMapper;
import com.easy.service.UserService;
import com.easy.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {


    @Autowired
    UserMapper userMapper;


    @Override
    @LogMethod(serviceName = "新增用户", recordParam = true, recordReturn = true)
    public User add(User user) {
        //新增数据
        userMapper.add(user);
        //通过主键查询数据库中的数据
        User result = userMapper.one(user.getId());
        return result;
    }

    @Override
    @LogMethod(serviceName = "删除用户", recordParam = true, recordReturn = true)
    @CacheEvict(value = "user", key = "#p0" ,allEntries = true)//清空value制定的所有实例
    public int del(Integer id) {
        return userMapper.del(id);
    }

    @CachePut(value = "user", key = "#p0.id")
    @Override
    @LogMethod(serviceName = "修改用户", recordParam = true, recordReturn = true)
    public User edit(User user) {
        userMapper.edit(user);
        User result = userMapper.one(user.getId());
        return result;
    }

    @Cacheable(value = "user", key = "#p0")//也可以#p0表示第一个参数
    @Override
    public User one(Integer id) {
        return userMapper.one(id);
    }

    @Override
    public List<User> all(User user) {
        return userMapper.all(user);
    }

    @Override
    public void page(Page page, User user) {
        int count = userMapper.pageCount(user);
        Object data = userMapper.page(page,user);
        page.setCount(count);
        page.setData(data);
    }
//设置新密码需要旧密码
    @Override
    @LogMethod(serviceName = "通过旧密码更新密码", recordParam = true, recordReturn = true)
    public String updatePassword(String token, PasswordParam param){
        //验证旧密码
        Object option = TokenUtil.getOption(token, SYS.TOKEN_KEY_ID);
        Integer userId = Integer.valueOf(option.toString());
        String password = userMapper.getoldPasswordById(userId);
        boolean result = PasswordUtil.checkPassword(param.getOldPassword(), password);
        if (!result) {
            return "旧密码错误";
        }else{
            //设置新密码
            String encryption = PasswordUtil.getEncryption(param.getNewPassword());
            userMapper.updatePassword(encryption, userId);
            return "新密码设置成功";
        }
    }
    //设置新密码无需旧密码
    @Override
    @LogMethod(serviceName = "通过邮箱验证码更新密码", recordParam = true, recordReturn = true)
    public String unknownUpdate(String token, PasswordParam param){
        //验证邮箱验证码
        Object option = TokenUtil.getOption(token, SYS.TOKEN_KEY_ID);
        Integer userId = Integer.valueOf(option.toString());
        User one = userMapper.one(userId);
        System.out.println(one);
        if (one.getEmailCaptcha() == null) {
            return "请先获取邮箱验证码";
        }
        String emailCaptcha = one.getEmailCaptcha();
        if (!param.getEmailCaptcha().equals(emailCaptcha)) {
            return "邮箱验证码错误";
        }
        //成功写入新密码
        String encryption = PasswordUtil.getEncryption(param.getNewPassword());
        userMapper.updatePassword(encryption, userId);
        return "新密码设置成功";
    }
    //获取验证码
    @Override
    @LogMethod(serviceName = "获取邮箱验证码", recordParam = true, recordReturn = true)
    public String getEmailCaptcha(String token, PasswordParam param){
        //获取验证码
        UUID uuid = UUID.randomUUID();
        String emailCaptcha = uuid.toString().substring(0, 5);
        new EmailUtil().sendEmail(param.getEmail(),emailCaptcha);
        //验证码写入数据库
        Object option = TokenUtil.getOption(token, SYS.TOKEN_KEY_ID);
        Integer userId = Integer.valueOf(option.toString());
        userMapper.updateEmailCaptcha(emailCaptcha, userId);
        return"获取验证码成功";
    }


    @Override
    public User getByToken(String token) {
        Object option = TokenUtil.getOption(token, SYS.TOKEN_KEY_ID);
        Integer userId = Integer.valueOf(option.toString());
        return userMapper.one(userId);
    }

    //删除图片
    // 定时任务：每天凌晨2点执行图片清理
    @Scheduled(cron = "0 0 2 * * ?")
    @Override
    @LogMethod(serviceName = "清除服务器冗余文件", recordParam = true, recordReturn = true)
    public void deleteImageUtil(){
        System.out.println("开始执行图片清理任务...");
        List<String> fileList = ImageUtil.getFileList();
        List<String> allImgUrls = userMapper.getAllImgUrls();
        List<String> list = new ArrayList<>();
        for(int i=0;i<allImgUrls.size();i++){
            String s = allImgUrls.get(i);
            s = s.substring(s.lastIndexOf("/") + 1);
            list.add(s);
        }
        for(String imgUrl:fileList){
            if(!list.contains(imgUrl)){
                ImageUtil.deleteFile(imgUrl);
            }
        }
    }
//
//    // 定时任务：每天凌晨2点执行图片清理
//    @Scheduled(cron = "0 0 2 * * ?")
//    public void scheduledDeleteUnusedImages() {
//        System.out.println("开始执行定时图片清理任务...");
//        deleteImageUtil();
//        System.out.println("定时图片清理任务执行完成");
//    }
//    // 定时任务：每小时检查一次（用于测试）
//     @Scheduled(cron = "0 0 * * * ?")
//    public void scheduledDeleteUnusedImagesHourly() {
//        System.out.println("开始执行每小时图片清理任务...");
//        deleteImageUtil();
//        System.out.println("每小时图片清理任务执行完成");
//    }
//    //每分钟
//    @Scheduled(cron = "0 * * * * ?")






}
